from django.utils import timezone
import logging
import types
import builtins
from apps.HttpTestcase.core.analysis_headers import analysis_args
import json
from apps.HttpTestcase.core.extractor import Extractor
from apps.HttpTestcase.core import functions
from apps.HttpTestcase.core.functions import *

logger = logging.getLogger('log')


class ExtMethodRunner(object):
    """
    方法运行类
    """

    def __init__(self):
        # 用于存放自定义方法列表
        self.ext_method = {}
        # 用于存放内置方法
        self.builtins = {}

        for name, value in vars(functions).items():
            # 判断是否是方法类型
            if isinstance(value, types.FunctionType):
                self.ext_method[name] = value
        for name, value in vars(builtins).items():
            if isinstance(value, types.BuiltinFunctionType):
                self.builtins[name] = value

    def run(self, http_session_params=None, ext_method_name=None, ext_method=None, expect_result=None, loop_count=None,
            ext_method_type=None):
        """
        Args:
            http_session_params： 提取的全局变量池
            ext_method_name： 方法名
            ext_method： 方法
            expect_result： 期望结果
            loop_count： 循环次数
            ext_method_type: 是否内置方法   True内置   False自定义
        """
        params = {**http_session_params.variable,
                  **http_session_params.output_Variables}
        logger.info(f'=============== 全局参数:【{params}】===============')
        ext_method = analysis_args(content=ext_method, variables=params)
        logger.info(f'=============== 开始执行方法:【{ext_method}】===============')

        # 截取方法名
        method_name = ext_method.split('(')[0]
        if ext_method_type == False and method_name in self.ext_method:
            logger.info(f'=============== 方法:【{ext_method}】类型为自定义===============')
            expect_result = analysis_args(content=expect_result, variables=params)
            try:
                expect_result = json.loads(expect_result) if expect_result else {}
                logger.info(f'=============== 方法期望结果:【{expect_result}】===============')
            except Exception as e:
                logger.info(f'=== 格式化实际结果:【{expect_result}】错误:【{e}】====')
            # 循环次数
            for i in range(loop_count):
                # execute_time = timezone.now()
                # 执行方法
                fun_run_result = eval(ext_method)
                if fun_run_result == None:
                    logger.info(f'=============== 方法:【{ext_method}】没有返回结果===============')
                else:
                    logger.info(f'=============== 方法:【{ext_method}】执行结果:【{fun_run_result}】===============')
                    # 提取实际结果与期望结果断言
                    # if isinstance(expect_result, dict) and expect_result.get('output'):
                    #     extractor = Extractor()
                    #     extractor.format_output(expect_result.get('output'))
                    #     extractor_variable = extractor.extract_output(fun_run_result)
                    #     http_session_params.update_output_variable(var=extractor_variable)
                    # else:
                    #     logger.info(f'=============== 期望结果错误 ===============')

                # 校验期望结果与实际结果

            # 组织返回值

            # 保存到报告表
